<template>
  <div>
    <el-card>
      <h2>📂 目录管理</h2>
      <!-- 语言切换 -->
      <el-select v-model="language" @change="changeLanguage">
        <el-option label="English" value="en" />
        <el-option label="中文" value="zh" />
      </el-select>
      <el-tree
          ref="treeRef"
          :data="treeData"
          node-key="path"
          :props="defaultProps"
          :expand-on-click-node="false"
          @node-click="handleFolderClick"
          @node-contextmenu="handleRightClick"
      >
        <template #default="{ node, data }">
          <el-icon v-if="data.type === 'folder'"><Folder /></el-icon>
          <el-icon v-else><Document /></el-icon>
          {{ node.label }}
        </template>
      </el-tree>
      <!-- 文件上传 -->
      <el-upload
          v-if="selectedPath && uploadVisable"
          class="upload-box"
          :action="`/fileManage/upload?targetDir=${selectedPath}`"
          :headers="authHeaders"
          :multiple="true"
          :show-file-list="true"
          :on-success="handleUploadSuccess"
          drag
      >
        <el-icon><UploadFilled /></el-icon>
        <div class="el-upload__text">拖拽文件到这里或 <em>点击上传</em></div>
      </el-upload>

      <!-- 右键菜单 -->
      <el-popover
          ref="contextMenuRef"
          v-model:visible="contextMenu.visible"
          trigger="manual"
          :virtual-ref="contextMenu.ref"
          :virtual-triggering="true"
          placement="bottom-start"
      >
        <el-button v-if="selectedFileType === 'folder'" @click="dialogVisible = true">📂 创建子文件夹</el-button>
        <el-button v-if="selectedFileType === 'folder'" @click="uploadVisable = true">上传文件</el-button>
        <el-button v-if="selectedFileType" @click="confirmDelete">🗑️ 删除</el-button>
        <el-button v-if="selectedFileType === 'file'" @click="downloadFile">📥 下载文件</el-button>
      </el-popover>

      <!-- 删除确认对话框 -->
      <el-dialog v-model="deleteDialogVisible" title="确认删除">
        <p>确定删除 <strong>{{ selectedPath }}</strong> 吗？</p>
        <template #footer>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteItem">删除</el-button>
        </template>
      </el-dialog>

      <!-- 创建文件夹 -->
      <el-dialog v-model="dialogVisible" title="创建文件夹">
        <el-input v-model="newFolderName" placeholder="输入文件夹名称" />
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createFolder">创建</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick ,computed} from "vue";
import { useI18n } from "vue-i18n";
import axios from "axios";
import { Folder, Document, UploadFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import http from "@/api/http";

const treeData = ref([]);
const defaultProps = { label: "label", children: "children" };
const selectedPath = ref("");  // 选中的目录路径
const selectedFileType = ref("");
const dialogVisible = ref(false);
const newFolderName = ref("");
const contextMenu = ref({ visible: false, x: 0, y: 0, ref: null });
const treeRef = ref(null);
const deleteDialogVisible = ref(false);
const { t, locale } = useI18n();
const language = ref(locale.value);
const uploadVisable = ref(false);  // 默认不显示，只有选定文件夹的时候显示，如果选到文件则隐藏


// 获取 Token 并设置请求头
const authHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem("token")}`
}));

// 获取目录结构
const fetchTreeData = async () => {
  const response = await http.get("/fileManage/directories");
  treeData.value = response.data.tree;
};

// 点击文件夹
const handleFolderClick = (data) => {
  if (data.type === "folder") {
    selectedPath.value = data.path;  // 选择的上传目录
  } else {
    uploadVisable.value = false;
  }
};

// 右键菜单
const handleRightClick = async (event, data) => {
  event.preventDefault();
  selectedPath.value = data.path;
  selectedFileType.value = data.type;

  contextMenu.value.visible = false;
  await nextTick();
  contextMenu.value.ref = {
    getBoundingClientRect: () => ({
      width: 0,
      height: 0,
      top: event.clientY,
      left: event.clientX,
      right: event.clientX,
      bottom: event.clientY,
    }),
  };
  contextMenu.value.visible = true;
};

// 创建文件夹
const createFolder = async () => {
  if (!newFolderName.value.trim()) return ElMessage.error("文件夹名称不能为空");

  try {
    await http.post("/fileManage/create-folder", {
      parentDir: selectedPath.value,
      newFolderName: newFolderName.value.trim(),
    });

    ElMessage.success("创建成功");
    dialogVisible.value = false;
    fetchTreeData();
  } catch (error) {
    ElMessage.error(error.response?.data?.error || "创建失败");
  }
};

// 上传文件成功
const handleUploadSuccess = () => {
  ElMessage.success("文件上传成功");
  fetchTreeData();
};

// 下载文件
/*const downloadFile = () => {
  const fileUrl = `/api/fileManage/download?filePath=${selectedPath.value}&authorization=${encodeURIComponent(localStorage.getItem('token'))}`;
  window.open(fileUrl, "_blank");
};*/
const downloadFile = async () => {
  try {
    const response = await http.get(`/fileManage/download?filePath=${encodeURIComponent(selectedPath.value)}`, {
      responseType: "blob", // 确保返回二进制数据
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`, // 认证
      },
    });

    let fileName = "报文.json";
    const contentDisposition = response.headers["content-disposition"];

    if (contentDisposition) {
      let match;

      // 1️⃣ **优先匹配 RFC 5987 规范的 UTF-8 编码**
      match = contentDisposition.match(/filename\*=\s*UTF-8''([^;]+)/);
      if (match) {
        fileName = decodeURIComponent(match[1]); // 处理 URL 编码的文件名
      } else {
        // 2️⃣ **匹配标准的 filename="xxx" 或 filename=xxx**
        match = contentDisposition.match(/filename="?([^";]+)"?/);
        if (match) {
          fileName = match[1]; // 这里不用 decodeURIComponent，因为它可能已经是普通文本
        }
      }
    }

    // 创建 Blob 对象
    const blob = new Blob([response.data], { type: response.headers["content-type"] });

    // 创建临时链接
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = fileName; // 下载文件名
    document.body.appendChild(link);
    link.click();

    // 释放 URL 对象
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
  } catch (error) {
    console.error("下载失败", error);
  }
};

// 删除确认
const confirmDelete = () => {
  deleteDialogVisible.value = true;
};

// 执行删除
const deleteItem = async () => {
  try {
    await http.post("/fileManage/delete", {
      targetPath: selectedPath.value
    });

    ElMessage.success("删除成功");
    deleteDialogVisible.value = false;
    fetchTreeData();
  } catch (error) {
    ElMessage.error(error.response?.data?.error || "删除失败");
  }
};

const changeLanguage = (val) => {
  locale.value = val;
  localStorage.setItem("lang", val);
};
onMounted(fetchTreeData);
</script>

<style scoped>
.upload-box {
  margin-top: 20px;
  border: 2px dashed #409eff;
  border-radius: 5px;
  padding: 20px;
  text-align: center;
}
</style>
